/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.imagepipeline.producers;

import com.facebook.common.memory.PooledByteBufferFactory;
import com.facebook.imagepipeline.image.EncodedImage;
import com.facebook.imagepipeline.request.ImageRequest;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.utils.net.Uri;

import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.Executor;

/**
 * resources that might not be part of the application's package.
 */
public class QualifiedResourceFetchProducer extends LocalFetchProducer {

  public static final String PRODUCER_NAME = "QualifiedResourceFetchProducer";

  private final DataAbilityHelper mContentResolver;

  public QualifiedResourceFetchProducer(
      Executor executor,
      PooledByteBufferFactory pooledByteBufferFactory,
      DataAbilityHelper contentResolver) {
    super(executor, pooledByteBufferFactory);
    mContentResolver = contentResolver;
  }

  @Override
  protected EncodedImage getEncodedImage(final ImageRequest imageRequest) throws IOException, DataAbilityRemoteException {
    final Uri uri = imageRequest.getSourceUri();
    final FileDescriptor fileDescriptor  = mContentResolver.openFile(uri,"r");
    InputStream inputStream = new FileInputStream(fileDescriptor);
    return getEncodedImage(inputStream, EncodedImage.UNKNOWN_STREAM_SIZE);
  }

  @Override
  protected String getProducerName() {
    return PRODUCER_NAME;
  }
}
